<!--
 * @Author: tenet 18742176629@163.com
 * @Date: 2024/7/15 上午9:25
 * @LastEditors: tenet 18742176629@163.com
 * @LastEditTime: 2024/7/15 上午9:25
 * @FilePath: G:/chain-link-api-front-admin/src/views/web3Tools/beautifulWallet\index.vue
 * @Description: 靓号钱包
-->
<template>
  <div class="container">
    <div class="title">{{ t('tools.BeautifulTitle') }}</div>
    <div class="Tips1 wrap">{{ t('tools.Tips1') }}</div>

    <div class="main wrap">
      <div class="top">
        <el-card class="control" style="">
          <el-form ref="ruleFormRef" :model="ruleForm" label-width="auto" label-position="top" status-icon>
            <el-form-item :label="t('tools.EnterBefore')" prop="callBackUrl">
              <el-input v-model.trim="ruleForm.before" :placeholder="t('tools.Before')" clearable/>
            </el-form-item>
            <el-form-item :label="t('tools.EnterAfter')" prop="callBackUrl">
              <el-input v-model.trim="ruleForm.after" :placeholder="t('tools.After')" clearable/>
            </el-form-item>
            <el-form-item :label="t('tools.Case')">
              <el-radio-group v-model="ruleForm.caseSensitive">
                <el-radio :value=true>YES</el-radio>
                <el-radio :value=false>NO</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item :label="t('tools.Thread')">
              <el-input-number v-model="thread" :min="1" :max="10" @change="handleChange"/>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="onStart" :loading="creatLoading">{{ t('button.Create') }}</el-button>
              <el-button type="warning" @click="onPause" :disabled="isPaused">{{ t('button.Pause') }}</el-button>
              <el-button type="danger" @click="onReset">{{ t('button.Reset') }}</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card class="info" style="">
          <ul>
            <li>
              <span class="label">难度</span>
              <span class="value">{{ difficulty }}</span>
            </li>
            <li>
              <span class="label">生成</span>
              <span class="value">{{ generateCount }} addresses</span>
            </li>
            <li>
              <span class="label">50%可能性</span>
              <span class="value">0 address</span>
            </li>
            <li>
              <span class="label">速度</span>
              <span class="value">{{ generateSpeed }} addr/s</span>
            </li>
            <li>
              <span class="label">状态</span>
              <span class="value">{{ statuesText }}</span>
            </li>
          </ul>

          <!--          进度条-->
          <el-progress :text-inside="true" :stroke-width="26" v-model:percentage="generateCountPercentage"/>
        </el-card>
      </div>


      <div class="footer wrap">
        <el-card class="item" style="padding: 10px" v-for="(item, key) in walletList" :key="key" v-show="showRes">
          <qrcode-vue :value="item.qrUrl" :size="80" :options="qrData.qrOptions"
                      style="margin-right: 10px"></qrcode-vue>
          <div class="right">
            <div class="top item_body">
              <el-input v-model="item.address" disabled style="max-width: 700px;width: 700px">
                <template #prepend>{{ t('tools.Address') }}</template>
                <template #append>
                  <el-button type="primary" @click="copyTextToClipboard(item.address)">{{ t('button.Copy') }}
                  </el-button>
                </template>
              </el-input>
            </div>
            <div class="footer item_body">
              <el-input v-model="item.privateKey" disabled style="max-width: 700px; width: 700px">
                <template #prepend>{{ t('tools.PrivateKey') }}</template>
                <template #append>
                  <el-button type="primary" @click="copyTextToClipboard(item.privateKey)">{{ t('button.Copy') }}
                  </el-button>
                </template>
              </el-input>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, reactive, unref, computed} from "vue";
import { ElMessage} from "element-plus";
import {useI18n} from "vue-i18n";
import {ethers} from "ethers";
import QrcodeVue from 'qrcode.vue';
import {useClipboard} from '@vueuse/core'

const {t} = useI18n();

// const worker = new Worker(new URL('./worker.js', import.meta.url));

onMounted(() => {
  // worker.onmessage = (event) => {
  //   const { address, privateKey } = event.data;
  //   updateUI({ address, privateKey });
  // };
})
const qrUrl = ref('')
const status = ref(false)
const isPaused = ref(false)
const showRes = ref(false) // 控制是否显示 结果
const loading = ref(false) //
const creatLoading = ref(false) // 生成地址时的 loading
const address = ref() // 地址
const privateKey = ref() // 私钥
const walletList = ref([]) // 钱包地址list
const thread = ref(1) // 控制线程
const statuesText = ref('Waiting') // 状态文本 Waiting | Running  | Finished
const generateCount = ref(0); // 定义已经生成的地址的计数器

const difficulty = computed(() => {
  return 16 ** (ruleForm.before.length + ruleForm.after.length);   // 难度
})

//  用计算属性 获取generateCount的值 获取百分比
const generateCountPercentage = computed(() => {
  console.log((generateCount.value / difficulty.value * 100).toFixed(2))
  return (generateCount.value / difficulty.value * 100).toFixed(2)
})

// 表单数据
const ruleForm = reactive({
  before: '',
  after: '',
  caseSensitive: false,
  threads: 1
})

async function onReset() {
  ruleForm.before = ''
  ruleForm.after = ''
  ruleForm.caseSensitive = false
  ruleForm.threads = 1
  showRes.value = false
  resetInfo()
}

// 清空Info数据
function resetInfo() {
  showRes.value = false
  //  清空 walletList
  walletList.value = [];
  statuesText.value = 'Waiting';
  generateCount.value = 0;
}

const timestamp_start = ref(0)// 开始时间
const timestamp_end = ref(0); // 结束时间

//  计算属性 计算timestamp_end - timestamp_start的差值,并用 generateCount / 差值得到计算速度
const generateSpeed = computed(() => {
  if (!generateCount.value && !timestamp_start.value && !timestamp_end.value) {
    return 0
  } else {
    return (generateCount.value / (timestamp_end.value - timestamp_start.value)).toFixed(2)
  }
})

// 开始生成地址
async function onStart() {
  // 初始化生成过程
  statuesText.value = 'Running';
  // resetInfo();

  // // 线程
  const workers = Array(ruleForm.threads).fill().map(() => {
    return new Promise((resolve) => {
      while (true) {
        const wallet = genAddress();
        if (wallet) {
          console.log(wallet)
          resolve(wallet);
          break;
        }
      }
    });
  });

  const wallet = await Promise.race(workers); // 使用Promise.race等待第一个生成符合条件的钱包的线程完成。
  console.log(wallet)
  if (wallet) {
    walletList.value.push({
      address: wallet.address,
      privateKey: wallet.privateKey,
      qrUrl: wallet.privateKey
    })

    showRes.value = true
    console.log(walletList.value)
    console.log(`生成了 ${generateCount.value} 个地址才找到符合条件的那个`); // 打印生成的地址数量
    statuesText.value = 'Finished';

    creatLoading.value = false;

  }
}
// 生成钱包地址
function genAddress() {
  generateCount.value += 1; // 每次生成钱包时计数器加1
  const wallet = ethers.Wallet.createRandom(); // 生成随机钱包
  let addr = wallet.address; // 获取钱包地址
  console.log(addr, generateCount.value)

  // 判断是否区分大小写 如果 ruleForm.caseSensitive 为 false 则转换为小写
  if (!ruleForm.caseSensitive) {
    address = address.toLowerCase();
  }

  // 前缀 和 后缀 的处理
  const prefix = ruleForm.caseSensitive ? ruleForm.before : ruleForm.before.toLowerCase();
  const suffix = ruleForm.caseSensitive ? ruleForm.after : ruleForm.after.toLowerCase();
  // 检查地址是否符合条件
  if ((!prefix || addr.slice(2).startsWith(prefix)) &&
      (!suffix || addr.endsWith(suffix))) {
    address.value = addr;
    privateKey.value = wallet.privateKey;
    qrUrl.value = wallet.privateKey
    status.value = true;
    return true;
  }
  return false;
}


const handleChange = (value) => {
  console.log(value)
}


// 暂停生成地址
async function onPause() {
  showRes.value = false;
  statuesText.value = 'Waiting';
  generateCount.value = 0;
}


// 更新UI状态
function updateUI(data) {
  address.value = data.address;
  privateKey.value = data.privateKey;
  qrUrl.value = data.privateKey;
  showRes.value = true;
  generateCount.value++;
}

const qrData = reactive({
  qrUrl: '',
  qrOptions: {
    /*
    二维码选项，可以根据需要进行配置
    L: 约 7% 或更少的错误能被纠正。
    M: 约 15% 或更少的错误能被纠正。
    Q: 约 25% 或更少的错误能被纠正。
    H: 约 30% 或更少的错误能被纠正。纠错能力越高，二维码的密集度也越高，但生成的二维码尺寸会相应增加。
    margin: 表示二维码的外边距，即二维码图案到画布边缘的距离，以模块为单位。默认为 4 个模块，可根据需要增加或减少
    scale: 表示二维码的放大倍数。默认为 4，意味着每个模块（方块）会被放大为 4 像素。增大放大倍数可以生成更大尺寸的二维码，也可以增加二维码的可读性，但会增加生成的二维码图像的尺寸
    */
    errorCorrectionLevel: 'H',
    margin: 2,
    scale: 4,
  }
})

// 当点击执行复制
const {text, copy} = useClipboard({legacy: true})
const copyTextToClipboard = async (val) => {
  console.log(val)
  try {
    await copy(unref(val));
    ElMessage.success(t('message.CopySuccess'));
  } catch (err) {
    console.error('Failed to copy text: ', err);
  }
};
</script>

<style scoped lang="less">
.wrap {
  width: 1024px;
}

.container {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;

  .title {
    color: #031a6e;
    font-size: 24px;
    font-weight: bold;
    margin: .2rem 0;
  }

  .Tips1 {
    text-align: left;
    margin: .5rem 0;
    font-size: 20px;
  }

  .main {
    height: 500px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;

    .top {
      width: 100%;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 5px;

      .control {
        width: 60%;
        height: 100%;
      }

      .info {
        width: 35%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: center;

        :deep(.el-card__body) {
          width: 100%;
          height: 100%;
          padding: 40px 20px;
          box-sizing: border-box;
        }

        :deep(.el-progress) {
          margin: 20px 0;
        }

        ul {
          width: 100%;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          align-items: center;

          li {
            width: 100%;
            height: 50px;
            line-height: 50px;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;

            span {
              text-align: left;
            }

            .label {
              width: 40%;
            }

            .value {
              width: 55%;
            }
          }
        }
      }
    }

    .footer {

      .item {
        width: 100%;

        :deep(.el-card__body) {
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          align-items: center;
        }
      }
    }
  }
}
</style>